package com.ice.ucenter.controller;

import com.ice.domain.model.response.CommonCode;
import com.ice.domain.model.response.QueryResponseResult;
import com.ice.domain.model.response.QueryResult;
import com.ice.domain.ucenter.RoleDO;
import com.ice.framework.web.BaseController;
import com.ice.ucenter.service.RoleService;
import com.ice.utils.Query;
import com.ice.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/ucenter/role")
@Controller
public class RoleController extends BaseController {
	String prefix = "system/role";
	@Autowired
	RoleService roleService;

	@GetMapping()
	String role() {
		return prefix + "/role";
	}

	@GetMapping("/list")
	@ResponseBody()
	public QueryResponseResult<RoleDO> list(@RequestParam Map<String, Object> params) {
		Query query = new Query(params);
		List<RoleDO> roles = roleService.list();
		Map<String, Object> map = new HashMap<String, Object>();
		int count = roleService.count(map);
		QueryResult<RoleDO> queryResult = new QueryResult<RoleDO>();
		queryResult.setList(roles);
		queryResult.setTotal(count);

		return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
	}

	@GetMapping("/add")
	String add() {
		return prefix + "/add";
	}

	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Long id, Model model) {
		RoleDO roleDO = roleService.get(id);
		model.addAttribute("role", roleDO);
		return prefix + "/edit";
	}

	@PostMapping("/save")
	@ResponseBody()
	R save(RoleDO role) {
		if (roleService.save(role) > 0) {
			return R.ok();
		} else {
			return R.error(1, "保存失败");
		}
	}

	@PostMapping("/update")
	@ResponseBody()
	R update(RoleDO role) {
		if (roleService.update(role) > 0) {
			return R.ok();
		} else {
			return R.error(1, "保存失败");
		}
	}

	@PostMapping("/remove")
	@ResponseBody()
	R save(Long id) {
		if (roleService.remove(id) > 0) {
			return R.ok();
		} else {
			return R.error(1, "删除失败");
		}
	}

	@PostMapping("/batchRemove")
	@ResponseBody
	R batchRemove(@RequestParam("ids[]") Long[] ids) {
		int r = roleService.batchremove(ids);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}
}
